<template>
  <div class="container">
    <div class="table-grid">
      <div 
        v-for="table in tableList" 
        :key="table.tableId"
        class="table-card"
        :style="{ backgroundColor: getStatusColor(table.tableStatus) }"
        @click="handleTableClick(table)"
      >
        <div class="card-content">
          <div class="table-id">{{ table.tableId }}</div>
          <div class="table-status">{{ table.tableStatus }}</div>
          <div class="table-type">{{ table.tableType }}</div>
        </div>
      </div>
    </div>

    <!--  就餐人数弹窗  -->
    <div v-if="showDialog" class="dialog-mask">
      <div class="dialog-container">
        <div class="dialog-header">
          桌台 {{ selectedTable?.tableId }} - 请输入就餐人数
          <button class="close-btn" @click="closeDialog">×</button>
        </div>
        <!-- 人数输入框 -->
        <div class="input-display">
          {{ peopleCount || '0' }}
        </div>

        <!-- 数字键盘 -->
        <div class="number-grid">
          <button 
            v-for="num in [1,2,3,4,5,6,7,8,9,0]" 
            :key="num"
            @click="handleNumberInput(num)"
            :class="{ 'zero-btn': num === 0 }"
          >
            {{ num }}
          </button>
          <button class="delete-btn" @click="peopleCount = ''">删除</button>
        </div>

        <!-- 确认按钮 -->
        <button 
          class="confirm-btn"
          :disabled="!isValidCount"
          @click="handleConfirm"
        >
          开台并点餐
        </button>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onActivated } from 'vue'
import { listAllTable } from '@/api/table'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { TableDTO } from '@/views/store/table/types'
import { getOrderByTable, makeNewOrder } from '@/api/order'

// 初始化加载数据
onMounted(() => {
  fetchTables()
})

// 每次页面激活时刷新
onActivated(() => {
  fetchTables() 
})

const router = useRouter()

const tableList = ref<TableDTO[]>([]);

// 获取桌位数据
const fetchTables = async () => {
  try {
  listAllTable().then((response) => {
    console.log('接口返回数据', response.data) // 确认数据结构
    tableList.value = response.data
    ElMessage({type: 'success',message: '获取数据成功'})
  })
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 状态颜色映射
const STATUS_COLOR_MAP = {
  '空闲': '#A8E6CF',  // 薄荷绿
  '待点菜': '#FFAAA5', // 浅珊瑚
  '用餐中': '#FFD3B6', // 浅桃色
  '待结账': '#A8C3D7', // 浅灰蓝
  '结帐中': '#D4A5A5'  // 浅玫瑰
}

// 弹窗相关状态
const showDialog = ref(false)
const selectedTable = ref<TableDTO | null>(null)
const peopleCount = ref('')

// 验证就餐人数
const isValidCount = computed(() => {
  const num = parseInt(peopleCount.value)
  return !isNaN(num) && num > 0 && num <= 99
})

// 桌台点击处理
const handleTableClick = async (table: TableDTO) => {
  switch (table.tableStatus) {
    case '空闲':
      selectedTable.value = table
      peopleCount.value = ''
      showDialog.value = true
      break;
    case '待点菜':
    case '用餐中':
    case '待结账':
      try {
        const res = await getOrderByTable(table.tableId)
        const currentOrder = res.data
        if (currentOrder) {
          router.push({
          name: 'ordering',
          params: { 
            orderId: currentOrder.orderId,
            tableId: table.tableId,
            people: currentOrder.peopleCount.toString()
          }
        })
        } else {
          ElMessage.warning('未找到对应的订单信息')
        }

      } catch (error) {
        console.error('获取订单失败:',error)
        await fetchTables() // 刷新数据
      }
      break;
    case '结账中':
      try {
        const res = await getOrderByTable(table.tableId)
        const currentOrder = res.data
        if (currentOrder) {
          router.push({
          name: 'payment',
          params: { 
            orderId: currentOrder.orderId,
            tableId: table.tableId,
            people: currentOrder.peopleCount.toString()
          }
        })
        } else {
          ElMessage.warning('未找到对应的订单信息')
        }

      } catch (error) {
        console.error('获取订单失败:',error)
        await fetchTables() // 刷新数据
      }
      break;
  }
  // if (table.tableStatus === '空闲') {
  //   selectedTable.value = table
  //   peopleCount.value = ''
  //   showDialog.value = true
  // }
}

// 数字输入处理
const handleNumberInput = (num: number) => {
  if (peopleCount.value.length < 2) {
    peopleCount.value += num.toString()
  }
}

// 确认操作
const handleConfirm = async () => {
  if (!isValidCount.value || !selectedTable.value) return

  try {
    const response = await makeNewOrder({
      tableId: selectedTable.value.tableId,
      people: parseInt(peopleCount.value)
    })
    const newOrder = response.data
    console.log('完整响应结构:', JSON.stringify(response, null, 2))
    console.log('业务数据:', newOrder)
    // 更新状态：
    // 直接修改本地数据（立即生效）
    const table = tableList.value.find(t => t.tableId === newOrder.table.tableId)
    if (table) table.tableStatus = '待点菜'

    // 刷新桌台列表数据
    // await fetchTables();
        // 跳转到点餐页面
        router.push({
          name: 'ordering',
          params: {
            orderId: newOrder?.orderId || 'temp_id',
            tableId: newOrder?.table?.tableId || '',
            people: (newOrder?.peopleCount ?? 0).toString()
          }
        });

        closeDialog();
        ElMessage.success('开台成功')
  } catch (error) {
    ElMessage.error('开台失败，请检查输入信息');
    console.error('开台操作失败:', error)
    alert('操作失败，请重试')
  }
}

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false
  selectedTable.value = null
  peopleCount.value = ''
}

// 状态颜色映射方法
const getStatusColor = (status) => {
  return STATUS_COLOR_MAP[status] || '#999999'
}


// 暴露方法供外部调用（后续可配合操作按钮）
const updateTableList = () => {
  fetchTables()
}

defineExpose({ updateTableList })
</script>

<style scoped>
.container {
  padding: 20px;
}

.table-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  width: 100%;
}

.table-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: all 0.3s;
  min-height: 150px;
  padding: 16px;
  position: relative;
}

.card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.table-id {
  position: absolute;
  top: 8px;
  left: 8px;
  font-weight: bold;
  font-size: 16px;
}

.table-type {
  position: absolute;
  bottom: 8px;
  left: 8px;
  color: #666;
}

.table-status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  font-weight: 500;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .table-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .table-grid {
    grid-template-columns: 1fr;
  }
}

.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-container {
  background: white;
  border-radius: 12px;
  width: 320px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.2);
}

.dialog-header {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0 8px;
}

.input-display {
  height: 60px;
  background: #f5f5f5;
  border-radius: 8px;
  margin: 10px 0;
  font-size: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: monospace;
}

.number-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin: 20px 0;
}

.number-grid button {
  height: 48px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 18px;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
}

.number-grid button:hover {
  background: #f0f0f0;
}

.zero-btn {
  grid-column: span 2;
}

.delete-btn {
  grid-column: span 1;
  background: #ffeaea !important;
  color: #F44336;
}

.confirm-btn {
  width: 100%;
  height: 48px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  opacity: 0.7;
}

.confirm-btn:not(:disabled):hover {
  opacity: 0.9;
}
</style>